package com.blue.filter;

import com.blue.pojo.User;
import com.blue.util.JacksonUtil;
import com.blue.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtFilter extends GenericFilterBean {
    @Autowired
    private RedisTemplate jsonRedisTemplate;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String jwt = request.getHeader("Authorization");

        if (jwt == null) {
            filterChain.doFilter(request, response);
            return;
        }


        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(jwt);
            userId = claims.getSubject();

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Token 非法");
        }

        String redisKey = "login:" + userId;
        Object redisValue = jsonRedisTemplate.opsForValue().get(redisKey);
        User user = JacksonUtil.convertValue(redisValue, User.class);

        if (user == null) {
            throw new RuntimeException("用户未登录!");
        }

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, null, null);
        SecurityContextHolder.getContext().setAuthentication(token);
        filterChain.doFilter(request, response);
    }
}
